/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.cenluan.activity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.cenluan.activity.comment.ActivityComment;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

public class ActivityService {
	/**
	 * 分页查询
	 * 
	 * @param pn
	 * @param show
	 *            要展示的内容：1.new，默认值，最新发起的。2.recent，近期即将开始的。3.mine我发起的
	 * @param createrId
	 *            活动发起人的id
	 * @param order
	 * @return
	 */
	static Page<Activity> paginate(int pn, String show, String createrId) {
		StringBuilder sql = new StringBuilder();
		List<Object> paras = new ArrayList<Object>();
		sql.append(" from t_activity a ");
		sql.append(" where a.state=? ");
		paras.add(Activity.STATE_ACTIVE);
		if ("recent".equals(show)) {
			sql.append(" and a.start>CURRENT_TIMESTAMP ");
			sql.append(" order by a.start asc ");
		} else if ("mine".equals(show)) {
			sql.append(" and a.createrId=? ");
			sql.append(" order by a.createTime desc ");
			paras.add(createrId);
		} else {
			sql.append(" order by a.createTime desc ");
		}
		return Activity.dao.paginate(pn, 20, "select a.*", sql.toString(),
				paras.toArray());
	}

	/**
	 * 获取用户最后一次发起活动的时间
	 * 
	 * @param userId
	 * @return
	 */
	static Date getUserLastSaveAvtivityTime(String userId) {
		return Db.queryDate("select max(createTime) from t_activity"
				+ " where createrId=?", userId);
	}

	/**
	 * 分页查询评论
	 * 
	 * @param pn
	 * @param activityId
	 * @return
	 */
	static Page<ActivityComment> paginateComment(int pn, String activityId) {
		StringBuilder sql = new StringBuilder();
		sql.append(" from t_activity_comment ");
		sql.append(" where activityId=? ");
		sql.append(" order by createTime asc ");
		return ActivityComment.dao.paginate(pn, 20, "select *", sql.toString(),
				activityId);

	}
}
